#include <dspSimulator/instruction/neg.h>

bool NEG::checkCondition(std::shared_ptr <DspMachine> dspMachine) {
    return checkStandardCondition(dspMachine);
}

void NEG::loadInstIRIntoJit(llvm::LLVMContext *llvmContext, llvm::Module *module,
                            std::shared_ptr <llvm::IRBuilder<>> irBuilder) {
    llvm::FunctionType *funcType = llvm::FunctionType::get(irBuilder->getVoidTy(), false);
    // --------------------------------- NEG (.unit) xsint, sint ---------------------------------------------
    {
        llvm::Function *neg = llvm::Function::Create(funcType, llvm::GlobalValue::ExternalLinkage, "NEGKind1",
                                                     module);
        llvm::BasicBlock *entryBB = llvm::BasicBlock::Create(*llvmContext, "entry", neg);
        irBuilder->SetInsertPoint(entryBB);

        auto dstRegPtr = getDstLoRegPtr(module, irBuilder);

        auto src2RegPtr = getSrc2LoRegPtr(module, irBuilder);
        auto src2Reg = irBuilder->CreateLoad(src2RegPtr);

        auto res = irBuilder->CreateSub(irBuilder->getInt32(0), src2Reg);
        irBuilder->CreateStore(res, dstRegPtr);
        irBuilder->CreateRetVoid();
    }
}

std::shared_ptr <Instruction> NEG::decode(std::shared_ptr <InstInfo> instInfo, u64 baseCycle) {
    std::shared_ptr <NEG> neg;
    auto dspInstInfo = std::dynamic_pointer_cast<DspInstInfo>(instInfo);
    bool isStandardInst = dspInstInfo->isStandardInstruction();
    if (isStandardInst) {
        auto data = vectorToBitSet<32>(dspInstInfo->getBits());
        if (checkBits<5>(data, 13, 0b00000) && checkBits<10>(data, 2, 0b0000110110) && existStandardCondition(data)) {
            neg = std::make_shared<NEG>(dspInstInfo->getAddress(), baseCycle);
            neg->creg_z = extractBits<4>(data, 28);
            neg->dst = extractBits<5>(data, 23).to_ulong();
            neg->src2 = extractBits<5>(data, 18).to_ulong();
            neg->x = data[12];
            neg->s = data[1];
            neg->p = data[0];
            if (neg->s == 0) {
                neg->funcUnit = FuncUnit::L1;
            } else {
                neg->funcUnit = FuncUnit::L2;
            }
            neg->instFormat = InstFormat::Kind1;
        }
    }
    return neg;
}

void NEG::executeCustom(std::shared_ptr <TargetMachine> targetMachine, ExecutePhase executePhase) {

}

std::shared_ptr <DspInstruction> NEG::clone() {
    return std::make_shared<NEG>(*this);
}

std::string NEG::toString() const {
    std::string res;
    res += getStandardConditionString() + " " + m_name + " " + FuncUnitName[static_cast<u32>(funcUnit)] + " ";
    if (instFormat == InstFormat::Kind1) {
        res += getSrc2Reg32Name() + "," + getDstReg32Name();
    }
    return res;
}